import logging
import uuid
from contextvars import ContextVar
from typing import Optional

from fastapi import Request

logger = logging.getLogger(__name__)

_request_ctx_var: ContextVar[Optional[Request]] = ContextVar("_request", default=None)
_request_id_ctx_var: ContextVar[str] = ContextVar("_request_id", default="")


def get_current_request() -> Optional[Request]:
    try:
        return _request_ctx_var.get()
    except LookupError:
        logger.warning("Attempting to access request outside of request context")
        return None


def get_request_id() -> str:
    try:
        return _request_id_ctx_var.get()
    except LookupError:
        return ""


def set_current_request(request: Request) -> None:
    request_id = str(uuid.uuid4())
    _request_ctx_var.set(request)
    _request_id_ctx_var.set(request_id)
    logger.debug(f"Request context set with ID: {request_id}")


def reset_current_request() -> None:
    try:
        request_id = get_request_id()
        _request_ctx_var.set(None)
        _request_id_ctx_var.set("")
        logger.debug(f"Request context reset for ID: {request_id}")
    except Exception as e:
        logger.error(f"Error resetting request context: {str(e)}")
